const { DataTypes, Model } = require('sequelize');

class Cart extends Model {
  // 计算小计
  getTotalPrice() {
    return (this.quantity * this.unitPrice).toFixed(2);
  }
}

// 初始化模型
const initCart = (sequelize) => {
    Cart.init({
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        userId: {
            type: DataTypes.INTEGER,
            allowNull: false,
            references: {
                model: 'users',
                key: 'id'
            }
        },
        productId: {
            type: DataTypes.INTEGER,
            allowNull: false,
            references: {
                model: 'products',
                key: 'id'
            }
        },
        quantity: {
            type: DataTypes.INTEGER,
            allowNull: false,
            defaultValue: 1,
            validate: {
                min: {
                    args: [1],
                    msg: '商品数量至少为1'
                },
                max: {
                    args: [999],
                    msg: '商品数量不能超过999'
                }
            }
        },
        unitPrice: {
            type: DataTypes.DECIMAL(10, 2),
            allowNull: false,
            validate: {
                min: {
                    args: [0],
                    msg: '单价不能为负数'
                }
            }
        }
    }, {
        sequelize,
        modelName: 'Cart',
        tableName: 'carts',
        timestamps: true,
        indexes: [
            {
                unique: true,
                fields: ['userId', 'productId']
            }
        ]
    });

    return Cart;
};

module.exports = initCart;